package com.yingsheng.bi.hks.basic.utils;

import io.minio.ObjectWriteResponse;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * 欣佳源的对象存储
 * 基于欣佳源的使用场景在OssUtils的基础上进一步封装
 *
 * @author root
 */
@ConfigurationProperties(prefix = "oss.xjy")
@Setter
@Component
public class XjyOssUtils implements InitializingBean {

    private String bucketName;

    private static volatile XjyOssUtils xjyOssUtils;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (XjyOssUtils.xjyOssUtils == null) {
            synchronized(XjyOssUtils.class) {
                if (XjyOssUtils.xjyOssUtils == null) {
                    XjyOssUtils.xjyOssUtils = this;
                }
            }
        }
    }

    public static ObjectWriteResponse putObject(byte[] content, String prefixPath, String objectName) {
        return OssUtils.putObject(content, getBucketName(), buildPath(prefixPath, objectName));
    }

    public static ObjectWriteResponse putObject(File file, String prefixPath, String objectName) {
        return OssUtils.putObject(file, getBucketName(), buildPath(prefixPath, objectName));
    }

    public static ObjectWriteResponse putObject(InputStream in, String prefixPath, String objectName) {
        return OssUtils.putObject(in, getBucketName(), buildPath(prefixPath, objectName));
    }

    public static String getSignedUrl(String prefixPath, String objectName) {
        return OssUtils.getSignedUrl(getBucketName(), buildPath(prefixPath, objectName));
    }

    public static InputStream getObject(String prefixPath, String objectName) {
        return OssUtils.getObject(getBucketName(), buildPath(prefixPath, objectName));
    }

    public static boolean deleteObject(String prefixPath, String objectName) {
        return OssUtils.deleteObject(getBucketName(), buildPath(prefixPath, objectName));
    }

    public static boolean exist(String prefixPath, String objectName) {
        return OssUtils.exist(getBucketName(), buildPath(prefixPath, objectName));
    }

    private static String buildPath(String prefix, String objectName) {
        if (prefix.endsWith("/")) {
            prefix = prefix.substring(0, prefix.length() -1);
        }
        if (!objectName.startsWith("/")) {
            objectName = "/" + objectName;
        }
        return prefix + objectName;
    }

    public static String getBucketName() {
        return XjyOssUtils.xjyOssUtils.bucketName;
    }


}
